import store from './index'
import request from '@/utils/drawutils/request';

import { ElMessage, ElMessageBox } from 'element-plus'
import { mergeArray } from '@/utils/drawdat/drawtool';

import eventBus from '@/utils/eventBus'

export default {
    state: {
      authRes: -1,
      bContinue: true ,  //是否继续执行脚本 questionbox 的结果及一些提问及错误的结果
    },
    mutations: {
        loaddrw( state, content ){
            loadDrw(  content  )
        },
        setAuthRes( state, authRes ){
            state.authRes = authRes
        },
    },


    actions: {
        //script是脚本功能
        async parseScript( { state, commit }, script  ){
          if( !state.isModeRun )  {
            // console.log( "执行脚本在设计模式立即返回" )
            return   //在设计状态就立即返回
          }
          if( state.authRes < 0 )  {
            //没有授权就立即返回
            //可以弹窗显示
            ElMessage({ type: 'error',  message: '请系统授权后使用按钮脚本功能!' })
            return   
          }          
          state.bContinue = true 
            let lines = script.split(/\r?\n|\r/);
            for( var i=0; i<lines.length; i++){
                let words = lines[i].trim().split(/\s+/);
                console.log( "script: ", words, state.bContinue )
                if( !state.bContinue ) break 

                if( words.length > 0){
                    let  func = words[0].toUpperCase(  )
                    console.log( "func: ", func )
                    if( func == "OPEN"){  // open /dir/filename.wdrw  打开一个图形文件 
                      await opendrw(  state, commit, words[1] )
                    }
                    if( func == "CONC"){    //conc  ctlid  带一个控制编号 定义的控制串中可以有宏变量， 形式是{ varname } 如{ yc3-54 }
                      await conc(  state, commit,  words )
                    }
                    if( func == "SETVALUE"){    //setvlaue  key  title strtitle 先取值，再赋值  title是子句
                        await  setvalue( state, commit,  words )  //
                    }
                    if( func == "QUESTIONBOX"){    
                      const  bRes = await  questionbox( words[1] )
                      state.bContinue = bRes 
                      // console.log( "answerquestion:",  bRes )
                    }  
                    if( func == "CONC3"){    //conc3 stationid ctlid
                      await conc3(  state, commit,  words )
                    }       
                    if( func == "CONS3"){    
                      await cons3(  state, commit,  words )
                    }   
                    if( func == "COND3"){    //conc  ctlid  带一个控制编号 定义的控制串中可以有宏变量， 形式是{ varname } 如{ yc3-54 }
                      await cond3(  state, commit,  words )
                    }                                                                              
                }
            }
            // console.log( lines )
        }
    },

}

async function opendrw( state, commit, filename  ){
    var parm = {filename : filename , projectid: state.projectid}
    console.log( "open drw: ", parm )
    const res = await request.post("/drwfile/loaddrwfile", parm )
    if( res.code === "1" ){
      // console.log( "open code", res.data )
      loadDrw( res.data )
      if( store.state.isModeRun ){
        store.dispatch('callData')
      }
      eventBus.$emit('eventScrollToTop')
          
      // ElMessage({ type: 'success',  message: "载入文件成功!" })
    }
    else{
      ElMessage({ type: 'error',  message: res.data })
    }

}

function loadDrw(  content  ){
      var webdrw = JSON.parse( content )
    
      clearRealData( webdrw.canvasData )
    //   console.log( "load 1",  webdrw.canvasData )
      mergeArray( webdrw.canvasData )   //可以将新版本中的新属性加到老版本中，避免由新版本引起的错误
    //   console.log( "load 2", webdrw.canvasData )

      store.commit('setCurComponent', { component: null, index: null })
      store.commit('setComponentData', webdrw.canvasData)
      store.commit('aceSetCanvasData', webdrw.canvasStyle)
      store.commit('recordSnapshot')
}

function clearRealData(  canvasData  ){
  console.log( "clear read data" )
      for (let i = 0; i < canvasData.length; i++ ){ 
          if( canvasData[i].component === 'VRealCurve' ){
            canvasData[i].propValue.option.xAxis.data = []

            for( var j=0; j<canvasData[i].propValue.option.series.length; j++){
              canvasData[i].propValue.option.series[j].data = [ ]
            }
          }
      }
}

//根据命令控制号进行命令串的下发
async function  conc( state, commit,  words ){
    if( words.length < 3 ){
    state.bContinue = false 
    return 
  }

  let prefix = getProjectPrefix(  words )
  if( prefix === "error" ){
    ElMessage({ type: 'error',  message: "conc中项目编码不存在！" })
    state.bContinue = false
    return
  }

  //根据前缀取项目编号 
    let parmprefix = "/drwproject/getproject_id?projectPrefix="+prefix
    const resprefix = await request.post( parmprefix  )
    if( resprefix.code === "0"){
      ElMessage( resprefix.msg )
      state.bContinue = false
      return
    }
    // console.log( "projects: ",   resprefix  )
    let project_id = resprefix.data[0].id

    let ctlid = words[1]
    let parm = "/ctlcmd/get?ctlid="+ctlid + "&project_id=" + project_id
    console.log( parm )
    const res = await request.get( parm  )
    // console.log( res )
    //判断返回的内容
    if( res.code === "0"){
      ElMessage( res.msg )
      state.bContinue = false
      return
    }

    let cmdstr = await conc_replacecmd( res.data[0].ctlstr )
    // console.log( "cmdstr", cmdstr )

    await ElMessageBox.confirm(
      res.data[0].descr,
      '命令提示：',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      }
    )
      .then(() => {
        let parm = "/ctlcmd/set?ctlstr="+cmdstr+"&ctlkey="+res.data[0].ctlkey
        request.post( parm ).then(res => {
          ElMessage({ type: 'success',  message: "命令发送成功！" })
        })

      })
      .catch(() => {
        state.bContinue = false
      })
    //执行命令
}

//2025-02-07
//conc3是为支持3000的开出而设计
async function  conc3( state, commit,  words ){
  if( words.length < 3 ){
    state.bContinue = false 
    return 
  }

  let stationid = words[1]
  let ctlid = words[2]
  console.log( "prefix before")  
  let prefix = getProjectPrefix(  words )
  if( prefix === "error" ){
    ElMessage({ type: 'error',  message: "conc3中项目编码不存在！" })
    state.bContinue = false
    return
  }
  let parm = "/ctlcmd3000/getdescr?ctlid="+ctlid + "&stationid="  + stationid + "&projectprefix=" + prefix
  console.log( parm )
  const res = await request.get( parm  )
  // console.log( res )
  //判断返回的内容
  if( res.code === "0"){
    ElMessage( res.msg )
    state.bContinue = false
    return
  }
  let taskname = res.data

  await ElMessageBox.confirm(
      res.data,
      '命令提示：',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      }
    )
    .then(() => {
        let controlstr = "conc " + stationid + " " + ctlid

        let parm = "/ctlcmd3000/sendctlstr?projectprefix="+ prefix +
        "&controlstr=" +  controlstr  + "&dbid="+  state.dbid

        request.post( parm ).then(res => {
          if( res.code === '1' )
            addCtlRecord( taskname )  //提交开出命令的记录
            ElMessage({ type: 'success',  message: "命令发送成功！" })
        })
    })
    .catch(() => {
      state.bContinue = false
    })
  
}  

async function  cons3( state, commit,  words ){
  if( words.length < 3 ){
    ElMessage({ type: 'error',  message: "参数个数不足！" })
    state.bContinue = false 
    return 
  }

  let stationid = words[1]
  let ctlid = words[2]
  let prefix = getProjectPrefix(  words )
  
  if( prefix === "error" ){
    await ElMessage({ type: 'error',  message: "cons3中项目编码不存在！" })
    state.bContinue = false
    return
  }

  let parm = "/ctlcmd3000/getdescr?ctlid="+ctlid + "&stationid="  + stationid + "&projectprefix=" + prefix
  console.log( parm )
  const res = await request.get( parm  )
  // console.log( res )
  //判断返回的内容
  if( res.code === "0"){
    ElMessage( res.msg )
    state.bContinue = false
    return
  }
  let taskname = res.data
  await ElMessageBox.confirm(
      res.data,
      '命令提示：',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      }
    )
    .then(() => {
        words.shift(  )   //popup cons3
        words.shift(  )   //popup stationid
        words.shift(  )   //popup ctlid
        let  ctlparm = words.join( " " )
        let controlstr = "cons " + stationid + " " + ctlid + " " + ctlparm

        let parm = "/ctlcmd3000/sendctlstr?projectprefix="+ prefix +
        "&controlstr=" +  controlstr  + "&dbid="+  state.dbid

        request.post( parm ).then(res => {
          if( res.code === '1' )
            addCtlRecord( taskname )  //提交开出命令的记录
            ElMessage({ type: 'success',  message: "命令发送成功！" })
        })
    })
    .catch(() => {
      state.bContinue = false
    })
  
}  


async function  cond3( state, commit,  words ){
  if( words.length < 3 ){
    ElMessage({ type: 'error',  message: "参数个数不足！" })
    state.bContinue = false 
    return 
  }

  let stationid = words[1]
  let ctlid = words[2]
  let prefix = getProjectPrefix(  words )
  if( prefix === "error" ){
    ElMessage({ type: 'error',  message: "cond3中项目编码不存在！" })
    state.bContinue = false
    return
  }    

  let parm = "/ctlcmd3000/getdescr?ctlid="+ctlid + "&stationid="  + stationid + "&projectprefix=" + prefix
  console.log( parm )
  const res = await request.get( parm  )
  // console.log( res )
  //判断返回的内容
  if( res.code === "0"){
    ElMessage( res.msg )
    state.bContinue = false
    return
  }
  let taskname = res.data

  words.shift(  )   //popup cons3
  words.shift(  )   //popup stationid
  words.shift(  )   //popup ctlid
  let  ctlparm = words.join( " " )
  let cmdstr = await conc_replacecmd( ctlparm )

  await ElMessageBox.confirm(
      res.data,
      '命令提示：',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      }
    )
    .then(() => {
        let controlstr = "cons " + stationid + " " + ctlid + " " + cmdstr

        let parm = "/ctlcmd3000/sendctlstr?projectprefix="+ prefix +
        "&controlstr=" +  controlstr  + "&dbid="+  state.dbid

        request.post( parm ).then(res => {
          if( res.code === '1' )
            addCtlRecord( taskname )  //提交开出命令的记录
            ElMessage({ type: 'success',  message: "命令发送成功！" })
        })
    })
    .catch(() => {
      state.bContinue = false
    })
  
}  

//替换控制串中的宏变量值，宏变量的形式是{ varname } 如{ yc3-54 }
async function  conc_replacecmd( str ){
    const regex = /\{([^{}]*)\}/g; // 匹配花括号中的内容
    const matches = [...str.matchAll(regex)]; // 获取所有匹配结果
    let varlist = matches.map(match => match[1]); // 提取每个匹配的内容
    
    let reslist = []
    for( var i=0; i<varlist.length; i++){
      reslist.push(  await  getvalue(varlist[i].trim()) )
    }

    return replaceCurlyBraceContents( str , reslist );

}

//将str花括号的内容替换为结果数组中的内容
function replaceCurlyBraceContents(str, replacements) {
    const regex = /\{([^{}]*)\}/g; // 匹配花括号和其中的内容
    let index = 0; // 用于追踪替换数组的索引

    // 使用 replace 方法逐一替换
    const result = str.replace(regex, () => {
        // 如果替换数组耗尽，保持原样
        if (index < replacements.length) {
            return replacements[index++];
        }
        return ""; // 如果没有更多替换内容，去掉花括号
    });

    return result;
}

async function  getvalue( key ) {
  let parm = "/redisdb/getvalue?dbid=0&key=" + key
  const res = await request.post( parm )
  return res.data
}

//给指定的键值赋值
async function  setvalue( state, commit, words ){   //
  let title = "输入新值"
  console.log( "words:", words )
  for(var i=0; i<words.length; i++) {
    console.log( words[i].toUpperCase )
    if( words[i].toUpperCase() === "TITLE" &&  i < words.length-1 ){
      title = words[i+1]
    }
  }

  let key = words[1]
  let parm = "/redisdb/getvalue?dbid=0&key=" + key
  console.log( "setvalue:",  parm )
  const res = await request.post( parm )
  // console.log( res )
  if( res.code = "1" ){
      setTimeout(() => {
        const inputElement = document.querySelector('.el-message-box__input .el-input .el-input__inner');
        if (inputElement) {
          // 选中输入框的内容
          inputElement.select();
        }
      }, 0);

      await ElMessageBox.prompt( title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: res.data,
        inputPlaceholder:  "输入新值",
        inputAttributes: {
          autofocus: true,
        }
      })
      .then(({ value }) => {
          let parm = "/redisdb/setvalue?dbid=0&key="+key+"&value=" + value
          request.post( parm ).then( res=>{
            if( res.code === "1" )
              ElMessage.success( "赋值成功!" )
            else{
              ElMessage.error( res.msg )
              state.bContinue = false
            }
              
          })
      })
      .catch(() => {
        state.bContinue = false
      })    
  }
}

//询问是否继续的功能
async function  questionbox( msg ){
    let bRes = false 
    await ElMessageBox.confirm(
      msg,
      '提示：',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      }
    )
      .then(() => {
        // console.log( "ok!" )
        bRes = true 
        // return true
      })
      .catch(() => {
        // console.log( "cancel!" )
        bRes = false
        // return false 
      })
      return  bRes

}

//2025-5-3 
//判断是否有 in 子句，有就返回 in 后面的值，没有就返回默认值
//判断输入新的prefix是否在项目中
function  getProjectPrefix (  words ) {
    let projectprefix = null
    let exist = words.some(word => word.toLowerCase() === 'in');
    if( exist ){
        const index = words.findIndex(word => word.toLowerCase() === 'in');
        if (index !== -1 && index < words.length - 1) {
          projectprefix = words[index + 1];
        }
    }
    else{
        return store.state.prefix;  
    }
    // 检查projectprefix是否存在于projects数组中
    if(store.state.projects && store.state.projects.length > 0) {
        const found = store.state.projects.some(project => project.prefix === projectprefix);
        if(!found) {
            projectprefix = "error"; // 如果不存在，使用默认prefix
            //ElMessage.warning(`项目前缀${projectprefix}不存在，使用默认前缀`);
        }
    }

    return projectprefix;
}

//2025-5-7
//添加开出控制的执行记录
function  addCtlRecord (  optaskname ) {
      let parm ={
        operid: store.state.operid,
        optaskname: optaskname,
        opername: store.state.opername,
        stationdescr: "N"
      }
      // let parm = "/hg9000operrecord/addrecord?operid="+ store.state.operid +
      //   "&optaskname='" +  optaskname  + "'&opername="+  store.state.opername + "&stationdescr=" + "N"
        console.log( "add record parm:", parm )
      request.post( "/hg9000operrecord/addrecord",   parm ).then(res => {
        if( res.code === '0' ){
            ElMessage({ type:'error',  message: "存储操作记录失败！" })
        }
      }).catch(error => {
        console.error('Request error:', error);
        ElMessage({ type:'error',  message: "请求发送失败，请检查网络连接！" });
      });
}